package com.zhou.dao;

import com.zhou.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Repository
public class JDBCUserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    public Map getMsg() {
        Map<String, Object> map = new HashMap<>();

        // 一个简单的返回总数的查询：
        int rowCount = this.jdbcTemplate.queryForObject(" select count(*) from user", Integer.class);

        // 一个带参数绑定的查询：
        Integer count = this.jdbcTemplate.queryForObject("select count(*) from user where department_id =?", Integer.class, 1);

        // 如果期望返回 POJO 实例， JdbcTemplate 需要一个 RowMapper ， 将查询结果集 ResultSet 映射成一个对象：
        String sql = "select * from user  where  id=?";
        User user = jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
//                user.setDepartment(resultSet.getObject("department", Department.class));
                user.setCreateTime(resultSet.getDate("create_time"));
                return user;
            }
        },1);
        map.put("rowCount", rowCount);
        map.put("count", count);
        map.put("user", user);
        return map;


    }
}